//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 张子国 on 15/11/11.
//  Copyright © 2015年 张子国. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    //定义一个webView
    
    let webView = UIWebView()
    //MARK: 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '17710317919@163.com' , document.getElementById('passwd').value = 'Ziguo5336118';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        setUpUI()
        //加载网页
        loadOAuthPage()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
   
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setUpUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
        }
    
}

//处理webView的所有协议方法
extension OAuthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        print(query)
        
      
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            print("进来了没有")
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络君正在睡觉,请稍后再来")
                return
            }
            
            
            
            //modal出来的页面 被dismiss掉 不会立即被回收
            //modal出来的页面 要注意dismiss
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
               
                //发出页面切换的通知
                
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "dfsf")
                
                //通知是同步的
                print("进来了")
            })
        }
        
        return false
        
    }
    
}

